<template>
  <div>
    <div>
      <div class="leftBar">
        <el-row class="tac">
          <el-col :span="12">
            <el-menu
              default-active="2"
              class="el-menu-vertical-demo"
              active-text-color="red"
            >
              <el-menu-item :index="JSON.stringify(2)" @click="selectAll">
                <span slot="title">全部</span>
              </el-menu-item>
              <el-menu-item v-for="item in baseClassifyList" :key="item" :index="item" @click="typeChange(item)">
                <span slot="title">{{ item }}</span>
              </el-menu-item>
            </el-menu>
          </el-col>
        </el-row>
      </div>

      <div class="picInfo">
        <el-row class="centers">
          <div class="choose">
            <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">当页全选 | 已选{{ bottomCheckboxFlagCount }}项 | 批量操作</el-checkbox>
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="showBatchChange">修改分组</el-button>&nbsp;&nbsp;
            <el-popconfirm
              title="确认删除所选全部吗？"
              confirm-button-type="warning"
              confirm-button-text="确定"
              class="customConfirm"
              @onConfirm="batchRemove"
            >
              <el-button slot="reference" type="danger" size="mini" icon="el-icon-delete">删除</el-button>
            </el-popconfirm>
            &nbsp;<el-button type="primary" size="mini" icon="el-icon-edit" @click="showAdd">新增</el-button>
            <div class="search">
              <el-input v-model="searchForm.fileName" size="small" class="search-input" placeholder="请输入视频名称" :clearable="true" />
              <el-button type="primary" icon="el-icon-search" size="mini" @click="searchGetList">搜索</el-button>
            </div>
          </div>
          <div class="formData">
            <el-col v-for="item in tableData.list" :key="item.id" :span="4" :offset="1" align="center">
              <div id="cards" class="choose-image-list">
                <div class="choose-image-item stys">
                  <video controls class="choose-image sty" :src="cfg.imageDomain + item.path" :poster="item.poster ? cfg.imageDomain + item.poster : cfg.imageDomain + item.path + '?vframe/jpg/offset/0/w/0/h/0'" />
                </div>
              </div>
              <div class="fileStys">
                <el-checkbox v-model="item.result" class="checkbox" @change="handleCheckedCitiesChange(item)" />
                <span v-if="item.updateTime" class="left font" :title="item.updateTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}')">{{ item.updateTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>&nbsp;&nbsp;
                <span class="right font" :title="parseInt(item.duration/60)+':'+((item.duration%60)<10?0:'')+parseInt(item.duration%60)+'  '+parseInt(item.fileSize / 1024 /1024)+'.'+parseInt(item.fileSize % 1024 % 1024 / 100)+'MB'">
                  <!--                  {{ parseInt(item.duration/60) }}:-->
                  <!--                  <span v-show="(item.duration%60)<10">0</span>{{ parseInt(item.duration%60) }}&nbsp;&nbsp;{{ parseInt(item.fileSize / 1024 /1024) }}.{{ parseInt(item.fileSize % 1024 % 1024 / 100) }}MB</span>-->
                  &nbsp;{{ parseInt(item.fileSize / 1024 /1024) }}.{{ parseInt(item.fileSize % 1024 % 1024 / 100) }}MB</span>
                <div><span class="right font">{{ item.fileName }}</span></div>
              </div>
              <div class="pads">
                <el-button type="text" @click="showUpdate(item)">编辑
                </el-button>
                <el-button type="text">
                  <el-link v-clipboard:copy="cfg.imageDomain + item.path" v-clipboard:success="clipboardSuccess" type="primary">
                    链接
                  </el-link>
                </el-button>
                <!--                <el-button type="text" @click="download(item)">下载 </el-button>-->
                <el-popconfirm
                  title="确认删除吗？"
                  confirm-button-type="warning"
                  confirm-button-text="确定"
                  class="customConfirm"
                  @onConfirm="remove(item)"
                >
                  <el-button slot="reference" type="text">删除</el-button>
                </el-popconfirm>
              </div></el-col>
          </div>
        </el-row>
        <el-pagination v-if="tableData.total > 0" class="pagination" :page-count="tableData.pageCount" :current-page.sync="tableData.pageNo" :limit.sync="tableData.pageSize" @current-change="pageChange" />

      </div></div>

    <!-- todo 调整表单字段 -->
    <el-dialog :close-on-click-modal="false" title="编辑" :visible.sync="updateDialog">
      <el-form ref="formData" :model="formData.props" :rules="formData.rules" label-width="180px">

        <el-form-item label="名称" prop="fileName">
          <el-input v-model="formData.props.fileName" placeholder="请输入名称" />
        </el-form-item>

        <el-form-item label="视频分类" prop="classificationId">
          <el-select v-model="formData.props.classificationId" placeholder="请选择分类" :clearable="true" transfer="true" :popper-append-to-body="false">
            <el-option
              v-for="item in baseClassifyList"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
          <el-button type="text" @click="addClassificationDialog = true">添加分组</el-button>
          <el-button type="text" @click="refresh">刷新</el-button>
        </el-form-item>

        <el-form-item label="视频封面" prop="poster">
          <el-button type="text" @click="chooseImgDialog = true">修改</el-button>
          <img v-if="formData.props.poster" class="img-preview" :src="cfg.imageDomain + formData.props.poster" alt="">
          <img v-else class="img-preview" :src="cfg.imageDomain + formData.props.path + '?vframe/jpg/offset/0/w/0/h/0'" alt="">
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateDialog = false">取 消</el-button>
        <el-button type="primary" :disabled="btnSubmitDisabled" @click="save">确 定</el-button>
      </span>
    </el-dialog>

    <!-- todo 调整表单字段 -->
    <el-dialog :close-on-click-modal="false" title="批量修改" :visible.sync="batchChangeDialog">
      <el-form ref="formData" :model="formData.props" :rules="formData.rules" label-width="180px">

        <el-form-item label="视频分类">
          <el-select v-model="formData.props.classificationId" placeholder="请选择分类" :clearable="true">
            <el-option
              v-for="item in baseClassifyList"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="batchChangeDialog = false">取 消</el-button>
        <el-button type="primary" :disabled="btnSubmitDisabled" @click="batchChangeType">确 定</el-button>
      </span>
    </el-dialog>

    <!-- todo 调整表单字段 -->
    <el-dialog :close-on-click-modal="false" title="新增分类" :visible.sync="addClassificationDialog" :append-to-body="true">
      <el-form ref="formData" :model="formData.props" :rules="formData.rules" label-width="180px">
        <el-form-item label="分类名称">
          <el-input v-model="formData.props.classificationId" placeholder="请输入分类名称" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addClassificationDialog = false">取 消</el-button>
        <el-button type="primary" :disabled="btnSubmitDisabled" @click="saveClassification">确 定</el-button>
      </span>
    </el-dialog>

    <!-- todo 调整表单字段 -->
    <el-dialog :close-on-click-modal="false" title="新增" :visible.sync="formData.formDialog">
      <el-form ref="formData" :model="formData.props" :rules="formData.rules" label-width="180px">
        <el-form-item label="视频" prop="path">
          <el-upload
            ref="videoUploader"
            class="upload-demo"
            :action="qiniuUploadPath"
            :before-upload="beforeUpload"
            :on-progress="uploadProgress"
            :data="qiniuDataObj"
            :show-file-list="false"
            :on-success="uploadSuccess"
            accept=".mp4"
          >
            <el-button type="text">点击上传</el-button>
          </el-upload>
          <el-progress v-if="videoUploadPercent !== null" :percentage="videoUploadPercent" />
          <video v-if="!!formData.props.path" controls class="video-upload-preview" :src="cfg.imageDomain + formData.props.path" />
        </el-form-item>
        <div>
          <el-form-item label="视频分类" prop="classificationId">
            <el-select v-model="formData.props.classificationId" placeholder="请选择分类" :clearable="true" transfer="true" :popper-append-to-body="false">
              <el-option
                v-for="item in baseClassifyList"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
            <el-button type="text" @click="addClassificationDialog = true">添加分组</el-button>
            <el-button type="text" @click="refresh">刷新</el-button>
          </el-form-item>
          <el-form-item label="视频封面" prop="poster">
            <el-button type="text" @click="chooseImgDialog = true">修改</el-button>
            <img v-if="formData.props.poster" class="img-preview" :src="cfg.imageDomain + formData.props.poster" alt="">
            <img v-else class="img-preview" :src="cfg.imageDomain + formData.props.path + '?vframe/jpg/offset/0/w/0/h/0'" alt="">
          </el-form-item>
          <el-form-item label="文件名" prop="fileName">
            <el-input v-model="formData.props.fileName" placeholder="请输入文件名" />
          </el-form-item>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="formData.formDialog = false">取 消</el-button>
        <el-button type="primary" :disabled="btnSubmitDisabled" @click="save">确 定</el-button>
      </span>
    </el-dialog>
    <choose-img
      :visible.sync="chooseImgDialog"
      @choose="chooseImg"
      @close="chooseImgDialog = false"
    />
    <el-dialog
      v-loading="loading"
      :close-on-click-modal="false"
      class="upload-img-dialog"
      element-loading-text="拼命上传中"
      :visible.sync="uploadProgressDialogVisible"
    />
  </div>
</template>

<script>
import request from '@/utils/request'
import clipboard from '@/directive/clipboard/index.js'
import ChooseImg from '@/components/wejoy/ChooseImg'
import { parseTime } from '@/utils/index' // Secondary package based on el-pagination

export default {
  name: 'ResPhotoLibList',
  components: { ChooseImg },
  directives: { clipboard },
  data() {
    return {
      props: {
        autoCropWidth: '',
        autoCropHeight: '',
        //  是否开启截图框宽高固定比例
        fixed: false,
        // 固定截图框大小 不允许改变
        fixedBox: false
      },
      qiniuDataObj: { token: '', key: '' },
      extensionNameCondition: '',
      fileNameCondition: '',
      bottomCheckboxFlagCount: 0,
      baseClassifyCondition: '',
      chooseImgDialog: false,
      batchIdList: [],
      prepareIdList: [],
      addClassificationDialog: false,
      batchList: [],
      chooseImageDialog: false,
      btnSubmitDisabled: false,
      updateDialog: false,
      batchChangeDialog: false,
      checkAll: false,
      isIndeterminate: false,
      uploadProgressDialogVisible: false,
      loading: false,
      baseClassifyList: '',
      videoUploadPercent: null,
      searchForm: {
        fileName: '',
        classificationId: '',
        type: 0
      },
      tableData: {
        pageNo: 1,
        pageSize: 12,
        total: 0,
        pageCount: 0,
        list: []
      },
      formData: {
        formDialog: false,
        // 表单字段, 请自行删除不需要的
        props: {
          extensionName: '',
          path: '',
          uploaderType: '',
          imgHeight: '',
          imgWidth: '',
          createUserId: '',
          fileSize: '',
          dataStatus: '',
          poster: '',
          fileName: '',
          classificationName: '',
          classificationId: '',
          type: 0
        },
        // 表单校验规则, 默认增加了必填, 请自行限制长度或者其他修改
        rules: {
          extensionName: this.formRules({ required: true }),
          path: this.formRules({ required: true }),
          uploaderType: this.formRules({ required: true }),
          imgHeight: this.formRules({ required: true }),
          imgWidth: this.formRules({ required: true }),
          createUserId: this.formRules({ required: true }),
          fileSize: this.formRules({ required: true }),
          sourceType: this.formRules({ required: true }),
          poster: this.formRules({ required: true }),
          dataStatus: this.formRules({ required: true }),
          fileName: this.formRules({ required: true }),
          classificationName: this.formRules({ required: true }),
          classificationId: this.formRules({ required: true })
        }
      },
      qiniuUploadPath: process.env.VUE_APP_UPLOAD_APK + '?uploadItem=resVideoLib'
    }
  },

  mounted: function() {
    this.getList({
      pageNo: 1,
      pageSize: this.tableData.pageSize
    })
    this.registerFilter('EnumStatus');
    this.registerFilter('EnumVideoResLibSourceType');
    this.getBaseClassify();
  },
  methods: {
    exceedLimit: function(files, fileList) {
      this.$message.warning('超出图片上传上限(10)')
    },
    clipboardSuccess() {
      this.$message({
        message: '复制链接成功',
        type: 'success'
      })
    },
    refresh() {
      this.getBaseClassify();
      this.$message.success('刷新成功');
    },
    beforeUpload(file) {
      const _this = this
      const nowDate = parseTime(new Date(), '{y}/{m}/{d}');
      const key = `videoResLib/${nowDate}/${file.uid}.mp4`;
      return new Promise((resolve, reject) => {
        request({
          method: 'post',
          url: '/multiMediaLib/videoResLib/getUploadToken',
          data: {
            path: key
          }
        }).then(response => {
          _this.qiniuDataObj = {
            token: response.data,
            key: key
          };
          resolve(true)
        }).catch(err => {
          console.log(err);
          reject(false)
        })
      });
    },
    uploadProgress(event, file, fileList) {
      this.videoUploadPercent = parseInt(event.percent);
    },
    uploadSuccess(response, file, fileList) {
      console.log(response)
      this.formData.props.extensionName = file.name.substr(file.name.lastIndexOf('.') + 1);
      this.formData.props.fileName = file.name.substr(0, file.name.lastIndexOf('.'));
      this.formData.props.path = response.data.key;
      this.formData.props.duration = response.data.duration;
      this.formData.props.fileSize = response.data.fileSize;
      console.log(this.formData.props)
    },
    chooseImg(file) {
      this.chooseImgDialog = false;
      this.formData.props.poster = file.path
    },
    pageChange: function(pageNo) {
      this.tableData.pageNo = pageNo;
      this.getList({
        pageNo: pageNo,
        pageSize: this.tableData.pageSize
      })
    },
    getList: function(req) {
      var _this = this;
      req.fileName = this.fileNameCondition;
      req.extensionName = this.extensionNameCondition;
      req.classificationId = this.baseClassifyCondition;
      request({
        url: '/multiMediaLib/videoResLib/getPageList',
        method: 'post',
        data: {
          pageNo: req.pageNo || this.tableData.pageNo,
          pageSize: req.pageSize || this.tableData.pageSize,
          ...this.searchForm
        }
      }).then(res => {
        const data = res.data;
        _this.tableData.total = data.total;
        _this.tableData.list = data.rows;
        _this.tableData.pageCount = data.pageCount;
        _this.tableData.pageNo = req.pageNo;
        this.prepareIdList = [];
        this.batchIdList = [];
        this.imagesList = [];
        this.isIndeterminate = false;
        this.checkAll = false;
        this.bottomCheckboxFlagCount = 0;
        for (let i = 0; i < res.data.rows.length; i++) {
          _this.tableData.list.result = false;
          this.prepareIdList.push(data.rows[i].id)
        }
      })
    },
    handleCheckAllChange(val) {
      if (val) {
        this.batchIdList = this.prepareIdList;
        this.tableData.list.forEach(item => {
          item.result = true;
        })
        this.bottomCheckboxFlagCount = this.batchIdList.length;
      } else {
        this.batchIdList = [];
        this.tableData.list.forEach(item => {
          item.result = false;
        })
        this.bottomCheckboxFlagCount = 0;
      }
    },
    handleCheckedCitiesChange(item) {
      if (item.result === true) {
        this.batchIdList.push(item.id);
        this.bottomCheckboxFlagCount++;
        if (this.tableData.list.length !== this.batchIdList.length) {
          this.isIndeterminate = true;
          this.checkAll = false;
        } else {
          this.isIndeterminate = false;
          this.checkAll = true;
        }
      } else if (item.result === false) {
        this.batchIdList.splice(this.batchIdList.indexOf(item.id), 1)
        this.bottomCheckboxFlagCount--;
        if (this.checkAll) {
          this.checkAll = false;
          this.isIndeterminate = true;
        } else if (this.batchIdList.length === 0) {
          this.isIndeterminate = false;
          this.checkAll = false;
        }
      }
    },
    getBaseClassify: function() {
      var _this = this;
      request({
        url: '/system/sysBaseParam/selectValueByUnicode?unicode=VIDEO_CLASSIFICATION',
        method: 'post'
      }).then(res => {
        _this.baseClassifyList = res.data.split(',');
      })
    },
    searchGetList: function() {
      this.getList({
        pageNo: 1,
        pageSize: this.tableData.pageSize
      })
    },
    showAdd: function() {
      this.getBaseClassify();
      this.formData.props = {
        id: '',
        extensionName: '',
        path: '',
        uploaderType: '',
        createUserId: '',
        duration: '',
        fileSize: '',
        status: '',
        fileName: '',
        sourceType: '1',
        poster: '',
        classificationId: '',
        type: 0
      }
      this.videoUploadPercent = null;
      this.imagesList = [];
      this.formData.formDialog = true;
    },
    showUpdate: function(data) {
      this.imagesList = [];
      this.getBaseClassify();
      this.formData.props = {
        id: data.id,
        extensionName: data.extensionName,
        path: data.path,
        uploaderType: data.uploaderType,
        createUserId: data.createUserId,
        duration: data.duration,
        fileSize: data.fileSize,
        status: data.status,
        fileName: data.fileName,
        sourceType: data.sourceType + '',
        poster: data.poster,
        classificationId: data.classificationId,
        type: 0
      };
      this.imagesList.push(this.formData.props);
      this.updateDialog = true;
    },
    typeChange(item) {
      this.searchForm.classificationId = item;
      this.getList({ pageNo: 1 });
    },
    selectAll() {
      this.searchForm.classificationId = '';
      this.getList({ pageNo: 1 });
    },
    showBatchChange() {
      if (this.batchIdList.length === 0) {
        this.$message.error('请勾选文件');
        return;
      }
      this.batchChangeDialog = true;
    },
    saveClassification() {
      var _this = this;
      this.baseClassifyList.push(this.formData.props.classificationId);
      const classification = this.baseClassifyList.join(',');
      request({
        url: '/system/sysBaseParam/setValueByUnicode',
        method: 'post',
        data: {
          uniCode: 'VIDEO_CLASSIFICATION',
          value: classification
        }
      }).then(res => {
        _this.addClassificationDialog = false;
        _this.$message.success('操作成功');
        _this.formData.props.classificationId = '';
        _this.getBaseClassify({
        });
      })
    },
    batchChangeType() {
      this.batchIdList.forEach(id => {
        const props = {
          id: id,
          classificationId: this.formData.props.classificationId
        };
        this.batchList.push(props);
      })
      this.batchSave();
    },
    save: function() {
      if (!this.formData.props.poster) {
        this.formData.props.poster = this.formData.props.path + '?vframe/jpg/offset/0/w/0/h/0'
      }
      var _this = this;
      this.disableBtn(this, 'btnSubmitDisabled');
      this.$refs.formData.validate(function(valid) {
        if (!valid) {
          return;
        }
        request({
          url: '/multiMediaLib/videoResLib/save',
          method: 'post',
          data: _this.formData.props
        }).then(res => {
          _this.formData.formDialog = false;
          _this.updateDialog = false;
          _this.batchChangeDialog = false;
          _this.$message.success('操作成功');
          _this.getList({
            pageNo: 1
          });
        })
      })
    },
    batchSave: function() {
      var _this = this;
      this.disableBtn(this, 'btnSubmitDisabled');
      if (_this.batchList.length === 0) {
        this.$message.error('未找到保存内容');
        return;
      }
      request({
        url: '/multiMediaLib/videoResLib/batchSave',
        method: 'post',
        data: {
          videoReslibMap: _this.batchList
        }
      }).then(res => {
        _this.formData.formDialog = false;
        _this.updateDialog = false;
        _this.batchChangeDialog = false;
        _this.$message.success('操作成功');
        _this.getList({
          pageNo: 1
        });
      })
    },
    download(data) {
      var path = data.path;
      var url = this.cfg.imageDomain;
      if (path.indexOf('.m3u8') !== -1 || path.indexOf('.mp4') === -1) {
        this.copyClipBoard(path + '?attname=' + data.fileName);
        this.$message.success('已复制资源地址，请使用相关工具下载！');
        return;
      }
      this.$message.warning('尝试下载！');
      if (url.indexOf('https') === -1) {
        url = url.toString().replace('http', 'https');
      }
      fetch(url + path).then(res => res.blob()).then(blob => {
        const a = document.createElement('a');
        document.body.appendChild(a);
        a.style.display = 'none';
        const url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = data.fileName;
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
        this.$message.success('下载成功！')
      });
    },
    batchRemove() {
      if (this.batchIdList.length === 0) {
        this.$message.error('请勾选文件');
        return;
      }
      this.batchIdList.forEach(id => {
        const props = {
          id: id,
          extensionName: '',
          path: '',
          uploaderType: '',
          createUserId: '',
          duration: '',
          fileSize: '',
          fileName: '',
          sourceType: '',
          poster: '',
          classificationId: '',
          status: -9
        };
        this.batchList.push(props);
      })
      this.batchSave();
    },
    remove: function(data) {
      var _this = this;
      request({
        url: '/multiMediaLib/videoResLib/delete?id=' + data.id,
        method: 'post',
        data: _this.formData.props
      }).then(res => {
        _this.$message.success('删除成功');
        _this.getList({
          pageNo: 1
        });
      })
    }
  }
}
</script>

<style>
  .choose {
    margin-left: 30px;
    float: left;
  }
  .leftBar {
    width: 40px;
    float: left;
  }
  .elTabs {
    width: 100%;
    float: left;
  }
  .formData {
    /*float: left;*/
    margin-top: 40px;

  }
  .picInfo {
    float: left;
    width: 91%;
  }
  .tac {
    float: left;
    width: 250px;
  }
  .font{
    font-weight: 400;
    font-style: normal;
    font-size: 12px;
    color:#CCCCCC;
    margin-top:5px
  }
  .centers {
    text-align: center;
    left: 6%;
  }
  .fileStys {
    width: 100%;
    display:block;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
    font-weight: 400;
    font-style: normal;
    font-size: 14px;
    text-align: left;
    margin-top: 10px;
  }
  .pad{
    min-width: 103%;
    max-height: 103%;
    overflow:hidden;
    padding-top:5px;
    display:flex;
    white-space:nowrap;
    overflow:hidden;
    justify-content:space-between;
    text-overflow:ellipsis;
  }
  .pagination {
    margin-left: 140px;
  }
  .stys img {
    border: 1px solid #f2f2f2;
    height:106%;
    width: 105%;
    margin-top: -2.2%;
    margin-left: -2.5%;
  }
  .pads {
    position: relative;
    padding-top: 5px;
    display:flex;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
    justify-content:space-between;
  }
  .img-preview {
    display: block;
    max-height: 100px;
  }
  .choose-image-list {
    margin-top: 40px;
    display: flex;
    flex-wrap: wrap;
  }
  .sty{
    max-width: 102%;
    max-height: 104%;
    min-width: 102%;
    min-height: 104%;
    margin-top: -1.2%;
    margin-left: -1%;
    height:200px;
  }
  .search{
    float: right;
    margin-right: 265px;
  }
  .video-upload-preview {
    max-height: 150px;
    max-width: 300px;
    min-width: 200px;
  }
</style>

